<template>
  <div class="flow">
    <!-- 员工信息卡片 -->
    <!-- <div class="employee-card"> -->
    <div class="formLook" :class="{ 'full-width': isFullWidth }">
      <div class="header">
        <!-- <span>入职办理</span> -->
        <TitleComponent title="转正申请" />
      </div>

      <div class="employee-avatar">
        <ImageComponent :src='userInfoForm.personPhoto' width="100px" height="100px" borderRadius="6px" />
      </div>

      <el-form label-width="100px" size="small">
        <div class="section-title">
          <span>基本信息</span>
        </div>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="员工账号：">
              <span>{{ userInfoForm.userName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工号：">
              <span>{{ userInfoForm.jobNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话：">
              <span>{{ userInfoForm.phoneNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工作邮箱：">
              <span class="ellipsis-text">{{ userInfoForm.mail }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="岗位名称：">
              <span>{{ userInfoForm.applicationPositonName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="岗位性质：">
              <span>{{ userInfoForm.jobNature }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门：">
              <span>{{ userInfoForm.deptName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职级：">
              <!-- <span>{{ userInfoForm.positionLevel }}</span> -->
              <span>{{ positionLevelLabel }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="直属领导：">
              <span>{{ userInfoForm.directLeaderName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最高领导：">
              <span>{{ userInfoForm.supremeLeaderName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入职日期：">
              <span>{{ userInfoForm.becomeJoinTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="转正日期：">
              <span>{{ userInfoForm.applyTime }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="section-title">
        <span>转正申请</span>
      </div>
      <el-form
        label-width="180px"
        size="small"
        label-position="left"
        v-if="route.query.text != '待转正查看'"
        style="margin-left: 30px"
      >
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="申请日期：">
              <span>{{ userInfoForm.applyTime }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="转正申请说明：">
              <span>{{ userInfoForm.applyDesc }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="试用期工作成绩：">
              <span>{{ userInfoForm.workCondition }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="试用期存在的问题及改进设想：">
              <span>{{ userInfoForm.idea }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="flowtab_info" v-if="isFullWidth">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="流程过程" name="流程过程">
          <steps
            :flowableDataList="flowableDataList"
            @submit="handleSubmit"
            @close="handleClose"
            :flowableBtns="flowableBtns"
          >
          </steps>
        </el-tab-pane>
        <el-tab-pane label="流程图" name="流程图">
          <bpmnViewer :flowData="flowDatas" :id="hightlightId" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import ImageComponent from "@/components/ImageComponent.vue";
import { reactive, ref } from "vue";
import steps from "@/components/step/index.vue";
import bpmnViewer from "@/components/Process/viewer/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { regularInfo } from "@/api/employeeRelations/regular.js";
import { formatDate } from "@/utils/index.js";
import TitleComponent from "@/components/TitleComponent.vue";
import {
  flowableTodo,
  flowablePhoto,
  flowableRecord,
  approveApi,
} from "@/api/flowableApi/flowableApi.js";
import useUserStore from "@/store/modules/user.js";
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const user = useUserStore().user;
const taskId = ref("接口取值");
const approvalBtns = ref(false); //审批按钮
const activeName = ref("流程过程");
const flowDatas = ref({});
// 审批意见
const auditOpinion = ref("");
// 留痕数据
const flowableDataList = ref([]);
// 审核按钮
const flowableBtns = ref([]);
// 下一个审批数据
const flowableTodoData = ref([]);
const procInsId = ref("");
// 高亮节点id
const hightlightId = ref("");
const userInfoForm = reactive({
  id: "",
  name: "", //姓名
  // sex: "", //性别
  phoneNumber: "", //联系电话
  mail: "", //邮箱
  userName: "", //员工账号
  jobNumber: "", //工号
  deptId: "", //任职部门id
  deptName: "", //任职部门名称
  positionLevel: "", //职级
  applicationPositonName: "", //岗位名称
  jobNature: "", //岗位性质
  directLeaderId: "", //直属领导id
  directLeaderName: "", //直属领导名称
  supremeLeaderId: "", //最高领导id
  supremeLeaderName: "", //最高领导名称
  joinType: "", //入职类型
  // socialSecurityScheme: "", //社保方案
  applicationSource: "", //应聘渠道
  salaryScale: "", //薪资标准
  otherSubsidy: "", //其他补贴
  // remark: "", //备注
  file: "", //附件
  applyTime: "", //转正申请日期
  applyDesc: "", //转正申请说明
  workCondition: "", //试用期工作成绩
  idea: "", //试用期存在的问题及改进设想
  status:
    "" /** 状态 0预入职，1入职审批中，2入职完成，3转正审批中，4转正完成，5取消入职 6取消转正*/,
  becomeJoinTime: "", //入职日期
});
const levelMap = {
  0: "初级",
  1: "中级",
  2: "高级",
};
const positionLevelLabel = computed(
  () => levelMap[userInfoForm.positionLevel] || ""
);

onMounted(async () => {
  if (route.query.id) {
    getInfo(route.query.id);
  }
  if (route.query.text == "查看") {
    approvalBtns.value = false;
  } else {
    approvalBtns.value = true;
  }
});
const isFullWidth = computed(() => {
  return route.query.workFlow == "1";
});
const init = async (processId) => {
  /**
   *  processId 流程实例id
      owner 指定人id
      role候选人id
      flowKey 流程key
   */
  let params = {
    owner: user.userId,
    role: user.userId,
    flowKey: "BECOME_MANAGEMENT",
  };

  try {
    // 留痕
    const recordRes = await flowableRecord({
      procInsId: processId,
      flowKey: "BECOME_MANAGEMENT",
    });
    if (recordRes.data.flowList.length > 0) {
      recordRes.data.flowList.sort((a, b) => {
        return Number(b.taskId) - Number(a.taskId) < 0;
      });
      flowableDataList.value = recordRes.data.flowList;
      if (flowableDataList.value.length > 0) {
        nextTick(() => {
          let x = document.querySelectorAll(".el-step__icon-inner");
          x.forEach((item, index) => {
            item.innerHTML = x.length - index;
          });
        });
      }
    }
    // 流程审批按钮
    const todoRes = await flowableTodo(processId, params);
    console.log(todoRes, "todoRes");

    if (todoRes.data.length > 0 && route.query.text == "审批") {
      // 审批

      flowableBtns.value = JSON.parse(todoRes.data[0].description)[0].btns;
      console.log(flowableBtns.value, "flowableBtns");

      flowableTodoData.value = todoRes.data[0];

      taskId.value = todoRes.data[0].taskId;
    }
  } catch (error) {
    console.error(error);
  }
};

const getInfo = (id) => {
  let processId = null;

  regularInfo(id).then(async (res) => {
    if (res.data) {
      Object.keys(res.data).forEach((item) => {
        if (res.data[item]) {
          userInfoForm[item] = res.data[item];
        }

        processId = res.data.processId;
        console.log(processId, "processIdprocessId");
      });
    }
    let params = {
      owner: user.userId,
      role: user.userId,
      flowKey: "BECOME_MANAGEMENT",
    };
    console.log(res.data, "res.data");
    if (res.data.processId) {
      const todoRes = await flowableTodo(res.data.processId, params);

      init(res.data.processId);
      console.log(todoRes, "todoRestodoRestodoRes");
      if (todoRes.data.length > 0) {
        // 审批
        // flowableBtns.value = JSON.parse(todoRes.data[0].description)[0].btns;
        console.log(todoRes.data[0], "todoRes.data[0]");
        flowableTodoData.value = todoRes.data[0];
        console.log(todoRes.data[0], "todoRes.data[0]");
        console.log(flowableTodoData.value, "flowableTodoData.value");
        taskId.value = todoRes.data[0].taskId;
      }
    }
  });
};
// 审批方法
const approveGoto = (data, item) => {
  approveApi(data, item.btnUrl).then((res) => {
    if (res.code == 200) {
      ElMessage.success(`${item.btnName}成功`);
      handleClose();
    } else {
      ElMessage.error(`${item.btnName}失败`);
    }
  });
};

const handleSubmit = (parameter) => {
  console.log(parameter, "parameter");

  let item = parameter.type;
  let comment = parameter.comment;

  // 参数
  let data = {
    accessory: [],
    accessoryList: [],
    agencyId: item.agencyId ? item.agencyId : "",
    agencyNextrole: "",
    // 当前人
    assignee: user.userId,
    // 审批意见
    auditOpinion: comment,
    // 当前时间
    auditTime: formatDate(new Date()).allDate,
    // 审批人 userName
    auditUserName: user.userName,
    beAssigner: "",
    beAssignerName: "",
    beAssignerRole: "",
    // 按钮名
    btnName: item.btnName,
    // user buid
    buId: user.dept.deptId,
    // 按钮id
    id: route.query.id,
    messageId: "",
    nextBuCode: "",
    otherFiles: [],
    processInstanceId: flowableTodoData.value.processInstanceId,
    status: item.status,
    taskId: flowableTodoData.value.taskId,
    // 按钮 vars
    vars: item.btnValue ? item.btnValue : "",
    flowKey: "BECOME_MANAGEMENT",
  };
  if (item.btnName == "保存") {
    approveGoto(data, item);
  } else {
    ElMessageBox.confirm(`是否要${item.btnName}这条转正申请审批?`, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        approveGoto(data, item);
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消",
        });
      });
  }
};
const handleClick = (tab) => {
  if (tab.props.name == "流程图") {
    flowablePhoto({
      procInsId: procInsId.value,
      flowKey: "BECOME_MANAGEMENT",
    }).then((res) => {
      flowDatas.value = res.data;
      hightlightId.value = res.data.nodeData[res.data.nodeData.length - 1].key;
    });
  }
};

const handleClose = () => {
  router.go(-1);
};
</script>

<style scoped lang="scss">
.container {
  margin: 0 auto;
  /* padding: 20px; */
}

.back-button {
  margin-bottom: 20px;
}

.employee-card {
  background-color: #fff;
  border-radius: 8px;
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
  padding: 20px;
  margin-bottom: 20px;
}

.employee-avatar {
  /* text-align: center; */
  text-align: left;
  margin-bottom: 20px;
  margin-top: 20px;
}

.el-divider--horizontal {
  margin: 24px 0;
}

.application-form {
  background-color: #fff;
  border-radius: 8px;
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
  padding: 20px;
}

.button-group {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  color: #606266;
}

:deep(.el-textarea__inner) {
  resize: none;
}
.section-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 3px solid #409eff;
  color: #16191d;
  margin-left: 10px;
}

.application-form {
  background-color: transparent;
}

.el-divider--horizontal {
  margin: 10px 0;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-form-item__label {
  font-weight: normal;
  color: #333;
  padding: 0 !important;
}

.el-form-item__content {
  display: flex;
  align-items: center;
}

.button-group {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-date-editor) {
  width: 100% !important;
}
.el-form-item__label {
  width: auto !important;
}
</style>
